package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;

import butterknife.BindView;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity {

    @BindView(R.id.webView_webview)
    WebView webViewWebView;
    @BindView(R.id.title_webview)
    TextView titleWebview;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;


    private String title;
    private String url;
    private Context mContext = this;
    private boolean isH5Title;

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }


    /**
     * Intent需要get的数据
     * <p>
     * 页面的标题                    IntentKey.INTENT_WEBVIEW_TITLE
     * 如果标题从网页拦截    IntentKey.INTENT_WEBVIEW_H5TITLE
     * 要加载的url                  IntentKey.INTENT_WEBVIEW_URL
     */
    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        title = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_TITLE);
        isH5Title = intent.getBooleanExtra(IntentKey.INTENT_WEBVIEW_H5TITLE, false);
        url = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_URL);
        if (!isH5Title) {
            titleWebview.setText(title);
        }
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        webViewWebView.getSettings().setJavaScriptEnabled(true);
        webViewWebView.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放
        webViewWebView.getSettings().setLoadWithOverviewMode(true);
        //解决图片不显示
        webViewWebView.getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webViewWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webViewWebView.getSettings().setDomStorageEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webViewWebView.getSettings().setAppCachePath(appCachePath);
        webViewWebView.getSettings().setAllowFileAccess(true);
        webViewWebView.getSettings().setAppCacheEnabled(true);
        webViewWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webViewWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                } else if (url != null && url.contains("#$index$#")) {  //跳首页
                    finish();
                } else if (url != null && url.contains("#$car$#")) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra("chooseCar", true);
                    startActivity(intent);
                } else if (url != null && url.contains("#$topUp$#")) {
                    startActivity(new Intent(mContext, ChargeMoneyActivity.class));
                    finish();
                } else if (url != null && url.contains("#$closeLotteryPage$#")) {
                    finish();
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, "网络错误，请重试", Toast.LENGTH_LONG).show();
            }

        });


        webViewWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String h5Title) {
                super.onReceivedTitle(view, h5Title);
                if (isH5Title) {
                    titleWebview.setText(h5Title);
                } else {
                    titleWebview.setText(title);
                }
            }
        });
        webViewWebView.loadUrl(url);

    }

    @OnClick({R.id.return_webview, R.id.close_webview})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_webview:
                if (webViewWebView.canGoBack()) {
                    webViewWebView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
                break;
            case R.id.close_webview:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webViewWebView.canGoBack()) {
            webViewWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
